#
#INJECT BY REGEX
#PMOD PLUGIN
#

import re, urllib, htmlentitydefs, urllib2
from urlparse import parse_qs

name = "Image Swap" #Name
web = "is.html"         #Web Page File

def setup(storage): 
    storage.url = "http://www.iconarchive.com/icons/fasticon/fruits/128/pineapple-icon.png"
    storage.img = urllib2.urlopen(storage.url).read()

def edit_REQUEST(request,storage):
    return None

def edit_RESPONSE(response,storage):
    if storage.enabled:
        if("content-type" in response.headers.keys()):
            print response.headers.getList("content-type")[0]
            if('image/' in response.headers.getList("content-type")[0]):
                img = storage.img
                response.headers.set("content-type","image/png",0)
                response.headers.set("content-length",str(len(img)),0)
                response.body = img
        else:
            if response.proxy.path.endswith(".png"):
                img = storage.img
                response.headers.set("content-type","image/png",0)
                response.headers.set("content-length",str(len(img)),0)
                response.body = img
                #response.body = re.sub("</html>","<div style='position:fixed;left:0px;top:0px;width:100%;background-color:white;'><center><img src='http://lostboy.net/wp-content/uploads/2009/05/defcon.png'></center></div></html>",response.body)

def do_PAGE(storage):
    out = ""
    if(storage.enabled):
        out+="<a href='is.html?disable'>Disable</a><br><br>"+urllib.quote(storage.url)+"<br><br>SETUP:<br><form action='is.html'>URL to image: <input type=text name=url></br><input type=submit value='Update' name=update></form>"
    else:
        out+="<a href='is.html?enable'>Enable</a>"
    return out

def handle_HTTP_RESPONSE(response,storage):
    if response.path.find("?") >= 0: #Probably editing something...
        query = response.path[response.path.find("?")+1:]
        if query=="enable":
            storage.enabled = 1
        if query=="disable":
            storage.enabled = 0
        if "update=Update" in query: #Update
            q = parse_qs(query)
            if 'url' in q:
                storage.url = q["url"][0]

